//
//  HomeController.swift
//  JianTingSwift
//
//  Created by zhibao on 2024/2/1.
//

import UIKit
import SnapKit
import AVFoundation
import CoreGraphics

class HomeController:SuperController{
    
    //手机号
    var phoneNum = ""
    var firstFlag = true
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if UserDefaults.standard.value(forKey: "privacy1") == nil {
            Helper.privacyAgreementShow()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getPayInfo()
        self.initView()
    }
    fileprivate func getPayInfo(){
        if IAPShare.sharedHelper().iap == nil {
            let dataSet = NSSet(array: [
                "com.yuliang.jianting.zhou",
                "com.yuliang.jianting.yue",
                "com.yuliang.jianting.ji",
                "com.yuliang.jianting.nian"
            ])
            IAPShare.sharedHelper().iap = IAPHelper(productIdentifiers: dataSet as? Set<AnyHashable>)
        }
        IAPShare.sharedHelper().iap.requestProducts { request, response in
            DLog(message: "response1==\(String(describing: response?.products))")
        }
        IAPShare.sharedHelper().iap.production = false
    }
    
    @objc fileprivate func shuoMingClick(){
        if MYGlobal.share().wechatFlag == 1 {
            Helper.alertShow(withTitle: "录音教程", withContent: "1、当在对话过程中想要进行录音，即可打开此APP，点击开始录音即可。\n2、如果两人相对较远，建议把手机听话筒放在两人中间以便录制俩人声音都清晰。\n3、录制完成（点击完成按钮）自动上传云端，若中途退出手机，当退出手机屏幕时候自动保存现有语音，下次启动APP时候自动上传云端。", withBtnTitle: "关闭"){ flag in
                
            }
            return
        }
        let controller = ShuoMingController()
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    @objc fileprivate func jiaoChengClick(){
        if MYGlobal.share().wechatFlag == 1 {
            Helper.alertShow(withTitle: "录音教程", withContent: "1、当在对话过程中想要进行录音，即可打开此APP，点击开始录音即可。\n2、如果两人相对较远，建议把手机听话筒放在两人中间以便录制俩人声音都清晰。\n3、录制完成（点击完成按钮）自动上传云端，若中途退出手机，当退出手机屏幕时候自动保存现有语音，下次启动APP时候自动上传云端。", withBtnTitle: "关闭"){ flag in
                
            }
            return
        }
        CGXPickerView.showStringPicker(withTitle: "选择教程", dataSource: ["去电教程","来电教程"], defaultSelValue: "去电教程", isAutoSelect: false, manager: nil) { value, row in
            let tempStr = value as! String
            var type = 1
            if tempStr == "去电教程" {
                type = 1
            }else{
                type = 2
            }
            let controller = JiaoChengController()
            controller.type = type
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    fileprivate func initView(){
        let phoneBtn = UIButton(type: .custom)
        phoneBtn.setImage(UIImage(systemName: "iphone.gen2.radiowaves.left.and.right.circle"), for: .normal)
        phoneBtn.setTitle("点击录音", for: .normal)
        phoneBtn.tintColor = UIColor.white
        phoneBtn.setTitleColor(UIColor.white, for: .normal)
        phoneBtn.addTarget(self, action: #selector(jiantingBtnClick), for: .touchUpInside)
        phoneBtn.backgroundColor = MYBlue
        phoneBtn.layer.cornerRadius = pixw(p:20)
        phoneBtn.titleLabel?.font = MY_SCALE_BoldFont(16)
        phoneBtn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: 10)
        self.view.addSubview(phoneBtn)
        phoneBtn.snp.makeConstraints { make in
            make.height.equalTo(pixw(p:100))
            make.width.equalTo(pixw(p:200))
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(pixw(p:-150))
        }
        
        let jcBtn = UIButton(type: .custom)
        jcBtn.setImage(UIImage(systemName: "togglepower"), for: .normal)
        jcBtn.setTitle("不会录音？点击我", for: .normal)
        jcBtn.tintColor = UIColor.white
        jcBtn.setTitleColor(UIColor.white, for: .normal)
        jcBtn.addTarget(self, action: #selector(jiaoChengClick), for: .touchUpInside)
        jcBtn.titleLabel?.font = MY_SCALE_FONT(12)
        self.view.addSubview(jcBtn)
        jcBtn.snp.makeConstraints { make in
            make.left.right.equalTo(phoneBtn)
            make.top.equalTo(phoneBtn.snp.bottom).offset(pixw(p:10))
            make.height.equalTo(pixw(p:20))
        }
        
        let xianchangTitles = [
            [
                "title":"捕捉点声音",
                "color":"#ff8070",
                "img":"waveform"
            ],
            [
                "title":"抓拍点视频",
                "color":"#50C17A",
                "img":"video"
            ],
            [
                "title":"截取点生活",
                "color":"#FF8825",
                "img":"livephoto"
            ],
        ]
        
        var tempView = jcBtn
        for i in 0 ..< xianchangTitles.count {
            let btn = UIButton(type: .custom)
            btn.layer.cornerRadius = pixw(p:20)
            btn.tintColor = UIColor.white
            btn.backgroundColor = MYColor.color(withHexString: xianchangTitles[i]["color"]!)
            btn.setTitle(xianchangTitles[i]["title"], for: .normal)
            btn.titleLabel?.font = MY_SCALE_LightFONT(15)
            btn.setImage(UIImage(systemName: xianchangTitles[i]["img"]!), for: .normal)
            btn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: pixw(p:10))
            btn.tag = 1000 + i
            btn.addTarget(self, action: #selector(btnClick(sender: )), for: .touchUpInside)
            self.view.addSubview(btn)
            btn.snp.makeConstraints { make in
                if i == 0 {
                    make.left.equalTo(pixw(p: 30))
                    make.right.equalTo(pixw(p: -30))
                    make.top.equalTo(tempView.snp.bottom).offset(pixw(p:40))
                }else if i == 1 {
                    make.left.equalTo(tempView)
                    make.right.equalTo(tempView.snp.centerX).offset(pixh(p: -10))
                    make.top.equalTo(tempView.snp.bottom).offset(pixw(p:20))
                }else {
                    make.left.equalTo(tempView.snp.right).offset(pixw(p: 20))
                    make.right.equalTo(pixw(p: -30))
                    make.top.equalTo(tempView)
                }
                make.height.equalTo(pixw(p:80))
            }
            tempView = btn
        }
        
        let tipLabel = UILabel()
        tipLabel.text = "友情提示:所有录音文件、照片、视频仅在绑定手机号码情况下才能自动上传云端永久保存!"
        tipLabel.font = MY_SCALE_MediumFONT(15)
        tipLabel.textColor = MYOrange
        tipLabel.numberOfLines = 0
        tipLabel.lineBreakMode = .byWordWrapping
        self.view.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 30))
            make.right.equalTo(pixw(p: -30))
            make.top.equalTo(tempView.snp.bottom).offset(pixw(p: 30))
        }
    }
    
    @objc fileprivate func btnClick(sender:UIButton){
        if sender.tag == 1000 {
            //录音
            let controller = LuYinListController()
            self.navigationController?.pushViewController(controller, animated: true)
        }else if sender.tag == 1001 {
            //录像
            let controller = LuXiangListController()
            self.navigationController?.pushViewController(controller, animated: true)
        }else if sender.tag == 1002 {
            //拍照
            let controller = PaiZhaoController()
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    @objc fileprivate func jiantingBtnClick(){
        
        if MYGlobal.share().wechatFlag == 1 {
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            let controller = LuYingZhongController()
            controller.docum = "luyin"
            self.navigationController?.pushViewController(controller, animated: true)
            return
        }
        if  UserInfoManager.shared().isLogin == false {
            YJLoginHelper.login(with: self)
            return
        }
        if UserInfoManager.shared().isVip() == false {
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                //去往购买中心
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
            return
        }
        
        let tempStr = UserDefaults.standard.value(forKey: "HomeShow")
        if  tempStr == nil {
            if firstFlag {
                Helper.firstShowTip { selectIndex in
                    if selectIndex == 1 {
                        self.firstFlag = false
                    }else{
                        UserDefaults.standard.setValue("HomeShow", forKey: "HomeShow")
                    }
                    self.phoneCall()
                }
            }else{
                self.phoneCall()
            }
        }else{
            self.phoneCall()
        }
    }
    
    fileprivate func phoneCall() {
        if UserInfoManager.shared().phone.count < 11 {
            QMUITips.showInfo("未绑定手机号，不能进行电话录音！")
            let controller = ChangePhoneController()
            controller.type = 2
            self.navigationController?.pushViewController(controller, animated: true)
            return
        }
        HttpHelper.sharedInstance().sendGet("api/call/number", parameters: [:]) { operation, respomseObject in
            if respomseObject.code == 1 {
                let repData = respomseObject.data as! [String:Any]
                let data =  repData["data"] as! [String:Any]
                if data.keys.count > 0 {
                    if let tempFirst = data["number"] {
                        self.phoneNum = tempFirst as! String
                        let phoneUrl = "telprompt:///\(tempFirst)"
                        UIApplication.shared.open(URL(string: phoneUrl)!, options: [:], completionHandler: { (success) in
                               if success {
                                   print("URL opened successfully")
                               } else {
                                   print("Failed to open URL")
                               }
                           })
                    }
                }else{
                    QMUITips.showError("获取数据失败，请稍后重试")
                }
            }else{
                QMUITips.showError(respomseObject.message)
            }
        } failure: { operation, error in
            
        }

    }
    
}




